// Copyright (c) 2007, Brian Duff

// See LICENSE for full license details.

package org.dubh.jdant;

import java.io.File;

import java.io.IOException;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

/**
 * An ant task that reads properties from a JDeveloper application file.
 * 
 * @author brian.duff@dubh.org
 */
public final class GetApplicationPropertiesTask extends Task
{
  private File _application;
  private boolean _echo;
  
  /**
   * Sets whether this task will echo the properties and values it is setting
   * to the ant log. <tt>false</tt> by default.
   * 
   * @param echo if <tt>true</tt> this task will echo to the log.
   */
  public void setEcho( boolean echo )
  {
    _echo = echo;
  }
  
  /**
   * Sets the application file to read. An application file is required.
   * 
   * @param application the application file to read.
   */
  public void setApplication( File application )
  {
    _application = application;
  }
  
  private void checkAttributes()
  {
    if ( _application == null )
      throw new BuildException( "application attribute is required." );
    
    if ( !_application.isFile() )
      throw new BuildException( "application file " + _application + " does not exist" );  
  }
  
  @Override
  public void execute() throws BuildException
  {
    checkAttributes();
    
    try
    {
      ApplicationFile a = new ApplicationFile( _application );
      
      if ( _echo )
      {
        log( "Application " + _application + " contains:" );
        for ( File f : a.projects() )
        {
          log( f.getPath() );
        }
      }      
    }
    catch ( IOException e )
    {
      throw new BuildException( 
        "Failed to read application " + _application + ":" + e.getMessage(), e );
    }
  }
}
